package com.da.javatest.demo.collection;

import java.util.LinkedHashMap;
import java.util.Map;

public class LruCache<K, V> {
    private static int MAX_CACHE_SIZE = 0;

    private Map<K, V> map;

    public LruCache(int maxCacheSize) {
        MAX_CACHE_SIZE = maxCacheSize;
        // 根据 cacheSize 和 填充因子计算cache的容量
        float LOAD_FACTORY = 0.75f;
        int capacity = (int)Math.ceil(MAX_CACHE_SIZE / LOAD_FACTORY) + 1;
        map = new LinkedHashMap<K, V>(capacity, LOAD_FACTORY, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > MAX_CACHE_SIZE;
            }
        };
    }

    public synchronized void put(K key, V value) {
        map.put(key, value);
    }

    public synchronized V get(K key) {
        return map.get(key);
    }

    public synchronized void remove(K key) {
        map.remove(key);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<K, V> entry : map.entrySet()) {
            sb.append(entry.getKey()).append("=")
                .append(entry.getValue()).append(" ");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        LruCache<Integer, String> cache = new LruCache<>(5);
        cache.put(1, "v1");
        cache.put(2, "v2");
        cache.put(3, "v3");
        cache.put(4, "v4");
        cache.put(5, "v5");
        cache.put(6, "v6");
        System.out.println(cache);
        cache.get(2);
        cache.put(7, "v7");
        System.out.println(cache);
    }
}